package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.DiaryDetail;
import com.ruoyi.livedemo.dto.DiaryMediaPayload;
import com.ruoyi.livedemo.dto.DiaryRequest;
import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.entity.DiaryEntry;
import com.ruoyi.livedemo.entity.DiaryMedia;
import com.ruoyi.livedemo.mapper.DiaryEntryMapper;
import com.ruoyi.livedemo.mapper.DiaryMediaMapper;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class DiaryService {

    private final DiaryEntryMapper diaryEntryMapper;
    private final DiaryMediaMapper diaryMediaMapper;

    public PagedResult<DiaryEntry> list(Long userId, int page, int size) {
        int offset = Math.max(page, 0) * size;
        List<DiaryEntry> entries = diaryEntryMapper.findPage(userId, offset, size);
        long total = diaryEntryMapper.countByUser(userId);
        return new PagedResult<>(total, entries);
    }

    public DiaryDetail get(Long userId, Long id) {
        DiaryEntry entry = diaryEntryMapper.findByIdAndUser(id, userId);
        if (entry == null) {
            throw new IllegalArgumentException("找不到日记");
        }
        List<DiaryMedia> media = diaryMediaMapper.findByDiary(entry.getId());
        return new DiaryDetail(entry, media);
    }

    @Transactional
    public DiaryDetail create(Long userId, DiaryRequest request) {
        DiaryEntry entry = new DiaryEntry();
        entry.setUserId(userId);
        entry.setEntryDate(request.getEntryDate());
        entry.setTitle(request.getTitle());
        entry.setWeather(request.getWeather());
        entry.setMood(request.getMood());
        entry.setContent(request.getContent());
        entry.setGratitude(request.getGratitude());
        entry.setCoverPath(request.getCoverPath());
        diaryEntryMapper.insert(entry);
        List<DiaryMedia> mediaList = persistMedia(entry.getId(), request.getMedia());
        return new DiaryDetail(entry, mediaList);
    }

    @Transactional
    public DiaryDetail update(Long userId, Long id, DiaryRequest request) {
        DiaryEntry entry = diaryEntryMapper.findByIdAndUser(id, userId);
        if (entry == null) {
            throw new IllegalArgumentException("找不到日记");
        }
        entry.setEntryDate(request.getEntryDate());
        entry.setTitle(request.getTitle());
        entry.setWeather(request.getWeather());
        entry.setMood(request.getMood());
        entry.setContent(request.getContent());
        entry.setGratitude(request.getGratitude());
        entry.setCoverPath(request.getCoverPath());
        diaryEntryMapper.update(entry);
        diaryMediaMapper.deleteByDiary(id);
        List<DiaryMedia> mediaList = persistMedia(id, request.getMedia());
        return new DiaryDetail(entry, mediaList);
    }

    @Transactional
    public void delete(Long userId, Long id) {
        diaryMediaMapper.deleteByDiary(id);
        diaryEntryMapper.delete(id, userId);
    }

    private List<DiaryMedia> persistMedia(Long diaryId, List<DiaryMediaPayload> payloads) {
        if (payloads == null || payloads.isEmpty()) {
            return Collections.emptyList();
        }
        // 将前端上传的多媒体信息写入 diary_media 表，保持有序与描述一致
        return payloads.stream().map(payload -> {
            DiaryMedia media = new DiaryMedia();
            media.setDiaryId(diaryId);
            media.setFilePath(payload.getFilePath());
            media.setMediaType(payload.getMediaType());
            media.setCaption(payload.getCaption());
            media.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
            diaryMediaMapper.insert(media);
            return media;
        }).collect(Collectors.toList());
    }
}
